//
//  LocalData.m
//  百度地图教程
//
//  Created by dllo on 15/8/28.
//  Copyright (c) 2015年 李东旭. All rights reserved.
//

#import "LocalData.h"
#import <BaiduMapAPI/BMapKit.h>

@interface LocalData () <BMKGeneralDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>
{
    /// 定义经纬度接受
    CGFloat _lat;
    CGFloat _lon;
}
/// 百度地图管理类对象
@property (nonatomic, strong) BMKMapManager *bmkManager;

/// 百度地图服务类对象
@property (nonatomic, strong) BMKLocationService *bmkService;

@end

@implementation LocalData

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        
    }
    
    return self;
}

- (BMKLocationService *)bmkService
{
    if (_bmkService == nil) {
        self.bmkService = [[BMKLocationService alloc] init];
    }
    
    return _bmkService;
}

/**
 * 建立定位请求：需要用户提供申请的key
 */
- (void)getLocationData:(NSString *)userKey
{
    // 第一步： 设置代理和key值(启动引擎)
    // 注意：start后面换成你申请的Appkey值
    self.bmkManager = [[BMKMapManager alloc] init];
    [self.bmkManager start:userKey generalDelegate:self];
    
    // 第二步: 启动定位服务
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyBest];
    
    self.bmkService.delegate = self;
    [self.bmkService startUserLocationService];
    
}

/// 开启GPS会自动走这个方法
#pragma mark - 地理定位代理方法
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _lat = userLocation.location.coordinate.latitude;
    _lon = userLocation.location.coordinate.longitude;

    // 停止更新
    [self.bmkService stopUserLocationService];
    
    // 拿到坐标后，用坐标推出城市名字
    CLLocationCoordinate2D pt;
    // 判断坐标是不是负数， 是的话纠正过来
    if (_lat < 0) {
        _lat = -_lat;
    }
    if (_lon < 0) {
        _lon = -_lon;
    }
    pt = (CLLocationCoordinate2D){_lat, _lon};
    
    // 启动geo搜索服务
    BMKGeoCodeSearch *geo = [[BMKGeoCodeSearch alloc] init];
    geo.delegate = self;
    
    // 反相geo检查信息
    BMKReverseGeoCodeOption *op = [[[BMKReverseGeoCodeOption alloc] init] autorelease];
    op.reverseGeoPoint = pt;
    
    // 根据地址坐标获取地理信息
    [geo reverseGeoCode:op];
    

}

#pragma mark - geo搜索服务代理方法
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    // 利用代理方法回调传递回去城市名字
    [self.delegate getLocalName:result.addressDetail.city];
    
    // 利用block传值
    self.myBlock(result.addressDetail.city);
//    NSLog(@"%@", result.addressDetail.city);
}

- (void)getLocalNameWithBlock:(void (^)(NSString *cityStr))cityName
{
    // zGrP7zxjq4BnWvdYuNVHrLQv
    [self getLocationData:@"zGrP7zxjq4BnWvdYuNVHrLQv"];
    self.myBlock = cityName;
}


@end
